#include "AnaDef.h"
#include "XGLUtils.h"
#include "AliTRDdEdxBaseUtils.h"
#include "style.h"

void drawTrain(const TString ilist, const Int_t nch = 6, char * cn="cc", const Int_t kpid=0)
{
  SetGlobalStyle(0);
  
  TCanvas *c1=new TCanvas(cn,cn,600,400);
 
  PadSetup(c1);
  c1->SetLeftMargin(0.14);
  c1->SetRightMargin(0.12);

  TChain *ch=XGLUtils::InputFiles(ilist,"tree");
  TH2D *    h1=new TH2D("h1","", 70,0.31, 5.1, 200,0, 6);

  /*
  if(kpid){
    h1=new TH2D("h1","", 70,0.31, 5.1, 200,0, 6);
  }
  else{
    //nothing to see above 5 GeV/c
    h1=new TH2D("h1","", 100,0.31, 20.1, 200,0, 6);
  }
  */

  AliTRDdEdxBaseUtils::BinLogX(h1->GetXaxis());
  ResetStyle(h1);

  h1->SetXTitle("p (GeV/c)");
  h1->SetYTitle("TRD dE/dx + TR (arb. units)");
  h1->GetXaxis()->SetMoreLogLabels();
  h1->GetXaxis()->SetNoExponent();

  //int ent = ch->Draw("trdsig:pTRD>>h1", Form("trdnch>=%d && trdncls/trdnch>20 && tpcncls>120 &&  (pidTPC2+pidTOF2+pidITS2<0.65) ", nch),"colz");
  int ent = -999;
  TString cut;
  if(kpid==0){
    cut=Form("trdnch>=%d && trdncls/trdnch>17 && tpcncls>120", nch);
  }
  else if(kpid==1){
    cut=Form("trdnch>=%d && trdncls/trdnch>17 && tpcncls>120 && pidV0>=1", nch);
  }
  else if(kpid==2){
    cut=Form("trdnch>=%d && trdncls/trdnch>17 && tpcncls>120 && kinV0>=1", nch);
  }

  ent = ch->Draw("trdsig:pTRD>>h1", cut,"colz");

  printf("kpid %d: cut %s ent %d\n", kpid, cut.Data(), ent);

  gPad->SetLogz(); 
  gPad->SetLogx(1); 
  h1->SetMinimum(1); h1->Draw("colz"); 

  TString tag(Form("trdTruncatedMean%s-nch%d-pid%d",cn,nch,kpid));
  tag.ReplaceAll(".","");

  c1->Print(tag+".eps");
  TFile *fout=new TFile(tag+".root","recreate");
  h1->Write();
  fout->Save();
  fout->Close();

}


int main(int argc, char *argv[])
{
  for(Int_t ii=0; ii<argc; ii++){
    printf("%d: %s\n", ii, argv[ii]);
  }

  if(argc!=5){
    printf("argc!=5\n"); return 1;
  }

  drawTrain(argv[1], atoi(argv[2]), argv[3], atoi(argv[4]));

  printf("done!\n");
  return 0;
}
